<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { useLabelAddOrUpdate, useLabelShow,sortEnableList } from '@fl/api/joint-api/flash-management'
import type { labelEditParam } from '@fl/api/joint-api/model/flash-management-types'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = withDefaults(defineProps<{
    areaList?: any[]
}>(), {
    areaList: [],
})
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })

const {areaList } = toRefs(props)

const formRef = ref()
const sortOptions = ref<any[]>([])
const title = ref('添加快讯标签')

const initialState = {
    labelName: '',
    classifyId: '',
    cityCode: '',
    areaCode: '',
}
const state = ref<labelEditParam>(cloneDeep(initialState))
const currentAreaList = computed(() => {
    return areaList?.value.find((item: any) => item.code === state.value.cityCode?.split('-')[0])?.areaList || []
})
// 详情
const { data: detail, isLoading } = useLabelShow(id)
watchEffect(() => {
    if (id.value) {
        title.value = '编辑快讯标签'
    }
    else {
        title.value = '新增快讯标签'
    }
    if (detail.value) {
        state.value = {
            ...detail.value,
            cityCode: detail.value?.cityCode ? `${detail.value?.cityCode}-${detail.value?.cityName || ''}` : '',
            areaCode: detail.value?.areaCode ? `${detail.value?.areaCode}-${detail.value?.areaName || ''}` : '',
        }
        console.log("🚀 ~ watchEffect ~ state.value:", state.value)

    }
})


// 查询列表
watchEffect(async () => {
    if (state.value?.cityCode||state.value?.areaCode) {
        const params = {
            cityCode: state.value.cityCode?.split('-')[0] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
        }
        const sortList = await sortEnableList(params)
        sortOptions.value = sortList.map((item) => {
            return {
                label: item.classifyName,
                value: item.id
            }
        })
    }
})

// 提交表单
const { isPending, mutate } = useLabelAddOrUpdate()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const target = sortOptions.value.find(item => state.value.classifyId === item.id)
        const params = {
            id: id.value ?? '',
            ...unref(state),
            classifyName: target.classifyName,
             cityCode: state.value.cityCode?.split('-')[0] || '',
            cityName: state.value.cityCode?.split('-')[1] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
            areaName: state.value.areaCode?.split('-')[1] || '',
        }
        console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                reset()
            },
        })
    }
}

function cancel() {
    reset()
}

function reset() {
    visible.value = false
    state.value = cloneDeep(initialState)
    formRef.value.formInstance.resetFields()
    id.value = ''
}

const columns: PlusColumn[] = [
     {
        // colProps: {
        //     span: 12,
        // },
        label: '所属城市',
        options: computed(() => {
            return areaList?.value.map((item: any) => {
                return {
                    label: item.name,
                    value: `${item.code}-${item.name}`,
                }
            })
        }),
        prop: 'cityCode',
        valueType: 'select',
    },
     {
        // colProps: {
        //     span: 12,
        // },
        label: '所属区域',
        options: computed(() => {
            return currentAreaList.value?.map((item: any) => {
                return {
                    label: item.name,
                    value: `${item.code}-${item.name}`,
                }
            })
        }),
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        label: '快讯标签',
        fieldProps: {
            maxlength: 10,
        },
        prop: 'labelName',
    },
    
    {
        label: '关联分类',
        prop: 'classifyId',
        valueType: 'select',
        options: computed(() => {
            return sortOptions.value
        }),
    },
]

const rules = {
    labelName: [
        {
            message: '请输入标签名称',
            required: true,
        },
    ],
      cityCode: [
        {
            message: '请选择所属城市',
            required: true,
        },
    ],
    classifyId: [
        {
            message: '请选择关联分类',
            required: true,
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="500"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt-20">
                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                >
                  <!-- <template #plus-field-cityCode>
                        <el-select v-model="state.cityCode"
                                   placeholder="请选择所属城市"
                                   clearable
                                   @change="cityChange"
                        >
                            <el-option v-for="item in cityOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-cityCode>
                        <el-select v-model="state.cityCode"
                                   placeholder="请选择所属城市"
                                   clearable
                                   @change="cityChange"
                        >
                            <el-option v-for="item in cityOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-classifyId>
                        <el-select v-model="state.classifyId"
                                   placeholder="请选择关联分类"
                        >
                            <el-option v-for="item in classifyOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template> -->
                </PlusForm>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
